package com.monitor.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.monitor.commons.HttpTookit;
import com.monitor.commons.enums.WhetherEnum;
import com.monitor.config.yunke.YunKeConfig;
import com.monitor.config.yunke.YunKeUtil;
import com.monitor.dao.IUserDao;
import com.monitor.modelExt.UserExt;
import com.monitor.pubInter.AbstractBaseService;
import com.monitor.pubInter.IBaseDao;
import com.monitor.pubInter.exception.SkException;
import com.monitor.searchExt.UserSearchExt;
import com.monitor.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;


/**
 * @author afeng
 * @Date 2025-03-17 10:50:14
 * @description UserService      用户信息
 */
@Service(value = "userService")
@Slf4j
public class UserServiceImpl extends AbstractBaseService<UserExt, UserSearchExt, String> implements IUserService {

    @Resource(name = "userDao")
    private IUserDao userDao;

    @Autowired
    private YunKeUtil yunKeUtil;
    @Autowired
    private YunKeConfig yunKeConfig;

    @Override
    public IBaseDao<UserExt, UserSearchExt, String> getDao() {
        return userDao;
    }

    /**
     * 更新 云客端没有设置用户id的 id
     * @throws SkException
     */
    @Override
    public void updateNoIdUser() throws SkException {
        UserSearchExt search = UserSearchExt.getInstance();
        List bindIn = new ArrayList();
        bindIn.add(WhetherEnum.NO.getValue());
        search.setIsBindIn(bindIn);
        List<UserExt> userExts = userDao.getAllList(search);
        userExts.forEach(userExt -> {
            //定义请求路径
            String url = yunKeConfig.getUrl() + "open/user/phonePass";
            //组装请求头
            long timestamp = new Date().getTime();
            Map<String, String> headsMap = yunKeUtil.getHeadMap(timestamp);
            //组装请求参数
            Map<String, Object> paramsMap = new HashMap<>();
            paramsMap.put("phone", userExt.getPhone());
            paramsMap.put("userId", userExt.getId());

            try {
                String res = HttpTookit.doPostHeader(url, paramsMap, headsMap);
                log.info("更新结果" + res);
                JSONObject resObject = JSONObject.parseObject(res);
                if (resObject.getBoolean("success")) {
                    userExt.setYkUserId(resObject.getString("data"));
                    userExt.setIsBind(WhetherEnum.YES.getValue());
                    userDao.update(userExt);
                }

            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        });
    }
}